iT邦幫忙

2025 iThome 鐵人賽

DAY 3
0
Vue.js

Vue 新手學習紀錄系列 第 3

Day 3|文章列表雛型:用 v-for 做出表格

  • 分享至 

  • xImage
  •  

目前資料暫時使用 json 的方式引入,考量到資料欄位很多,最後決定用最樸實的表格呈現,先來看看成果好了
https://ithelp.ithome.com.tw/upload/images/20250917/20177929WKqebWm23y.png

建立表格元件

在 src/components 中新增一個 PostTable.vue 的檔案

<template>
    <table class="post-table">
        <thead>
            <tr>
                <th>學校</th>
                <th>系所</th>
                <th>年度</th>
                <th>日期</th>
                <th>Score</th>
                <th>結果</th>
                <th>來源</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="post in posts" :key="post.pId">
                <td>{{ post.pSchool }}</td>
                <td>{{ post.pDep }}</td>
                <td>{{ post.pYear }}</td>
                <td>{{ post.pDate }}</td>
                <td>{{ post.pScore ?? '-' }}</td>
                <td>{{ post.pResult1 }}</td>
                <td>
                    <a v-if="post.pURL" :href="post.pURL" target="_blank">來源</a>
                </td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
    const props = defineProps({
        posts: { type: Array, default: () => [] }
    })
</script>

在 App.vue 中插入表格和資料

<script setup>
import Header from './components/Header.vue'
import posts from './data/data.js'
import PostTable from './components/PostTable.vue'

</script>

<template>
  <Header />
  <main>
    <h2>經驗分享</h2>
    <PostTable :posts="posts" />
  </main>
</template>

v-for 和 v-if

  • v-for: 用來重複渲染物件,就是 for 迴圈的概念啦。:key 要記得寫,可以幫助 Vue 追蹤每個元素,避免錯亂。
  • v-if: 控制要不要渲染某一段 DOM

Props: 由外向內傳遞資料

上面 code 會看到 props,它到底要幹嘛勒?
props 是拿來傳資料的,而且是從父元件傳到子元件,這裡的父元件是 App.vue 那一個,而子元件就是 PostTable.vue。目前資料會放在父元件是因為可能會有其他功能會用到資料,這樣可以統一從父元件的地方傳資料到子元件。

小結

  • v-for 和 v-if 應用
  • props 資料傳遞

上一篇
Day 2|首頁 Layout:建立網站 Header
系列文
Vue 新手學習紀錄3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言